import Vue from 'vue'
import VueRouter from 'vue-router'
// 懒加载
const Login = () =>
    import ('@/views/login/Login.vue')
const Layout = () =>
    import ('@/views/layout/index.vue')
const Home = () =>
    import ('@/views/home/Home.vue')
const User = () =>
    import ('@/views/user/User.vue')
const Search = () =>
    import ('@/views/search/Search.vue')
const SearchResult = () =>
    import ('@/views/search/SearchResult.vue')
const ArticleDetail = () =>
    import ('@/views/articleDetail/ArticleDetail.vue')
const UserEdit = () =>
    import ('@/views/user/UserEdit.vue')
const Chat = () =>
    import ('@/views/chat/Chat.vue')
import { getToken } from '@/utils/token.js'


Vue.use(VueRouter)

const routes = [{
    path: '/',
    redirect: '/layout/home', //默认显示layout和layout下的首页
}, {
    path: '/login',
    component: Login
}, {
    path: '/layout',
    component: Layout,
    children: [{
        path: 'home',
        component: Home,
        meta: {
            scrollT: 0, //保存首页离开时滚动条的位置
        }
    }, {
        path: 'user',
        component: User
    }]
}, {
    path: '/search',
    component: Search
}, { //搜索结果页
    path: '/search_result/:keyword',
    component: SearchResult
}, { //文章详情页
    path: '/detail',
    component: ArticleDetail
}, {
    // 用户编辑页面
    path: '/useredit',
    component: UserEdit
}, {
    // 聊天页面
    path: '/chat',
    component: Chat
}]

const router = new VueRouter({
    routes
})


// 路由-全局前置守卫（在路由发送真正跳转之前，执行次函数）
//此函数可以决定路由是否跳转/取消/强制中断，切换到别的路由
router.beforeEach((to, from, next) => {
    // 如果已经登录了，不要切换到登录页面
    if (getToken() && to.path === '/login') {
        // next(false) //留在原地，什么都不做
        next('/layout/home')
    } else {
        next() //其他情况放行
    }
})


export default router